﻿using Microsoft.AspNetCore.Mvc;
using NetTopologySuite.Algorithm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Attributes;
using ZhonTai.Admin.Core.Consts;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Domain.Patrol;
using ZhonTai.Admin.Services.Patrol.Dto;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;

namespace ZhonTai.Admin.Services.Patrol
{
    /// <summary>
    /// 表单服务
    /// </summary>
    [Order(11)]
    [DynamicApi(Area = AdminConsts.AreaName)]
    public class FormService : BaseService, IFormService, IDynamicApi
    {
        private IFormRepository _formRepository => LazyGetRequiredService<IFormRepository>();
        private IFormAndItemRepository _formAndItemRepository=>LazyGetRequiredService<IFormAndItemRepository>();
        
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<long> AddAsync(FormAddInput input)
        {
            var entity = Mapper.Map<FormEntity>(input);
            var item = await _formRepository.InsertAsync(entity);
            return item?.Id ?? 0;
        }

        /// <summary>
        /// 修改
        /// 目前无限制
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateAsync(FormUpdateInput input)
        {
            var entity = await _formRepository.GetAsync(input.id);
            Mapper.Map(input, entity);
            await _formRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<FormOutput>> GetPageAsync(PageInput<FormGetPageDto> input)
        {

            var list = await _formRepository
               .Select
               .ToListAsync();

            var data = new PageOutput<FormOutput>()
            {
                List = Mapper.Map<List<FormOutput>>(list),
                Total = 0
            };
            return data;
        }


        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<FormDetailOutput> GetAsync(long id)
        {
            var entity = await _formRepository.Select.Where(o=>o.Id == id).Include(o=>o.Controls).ToOneAsync();
            var output = Mapper.Map<FormDetailOutput>(entity);
            return output;
        }

        /// <summary>
        /// 设置表单项
        /// </summary>
        /// <returns></returns>
        [AdminTransaction]
        public async Task SetItemsAsync(FormAddItemInput input)
        {
            //1.找到表单下所有的项
            var entity = await _formRepository.GetAsync(input.FormId);
            if(!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("该表单不存在或已被删除！");
            }
            //2.查询表单项
            var itemsIds = await _formAndItemRepository.Select.Where(o => o.FormId == input.FormId).ToListAsync(m => m.ItemId);
            //
            var inputItemIds = input.Controls.Select(o => o.id).ToArray();
            //删除不包含的
            var delIds = itemsIds.Where(o=>!inputItemIds.Contains(o));
            if(delIds.Any())
            {
                await _formAndItemRepository.DeleteAsync(o => o.FormId == input.FormId && delIds.Contains(o.ItemId));
            }
            //新增
            var insertItems = new List<FormAndItemEntity>();
            var insertIds = inputItemIds.Where(o => !itemsIds.Contains(o));
            if(insertIds.Any())
            {
                foreach( var itemId in insertIds)
                {
                    insertItems.Add(new FormAndItemEntity()
                    {
                        FormId = input.FormId,
                        ItemId = itemId
                    });
                }
                await _formAndItemRepository.InsertAsync(insertItems);
            }
        }
    }
}
